﻿using System;
using log4net;
using Reactor.Exceptions;
using Reactor.Resources;

namespace Reactor.ServiceHost
{
    class Program
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(Program));

        static void Main(string[] args)
        {
            try
            {
                if (Log.IsDebugEnabled) Log.DebugFormat("Command line: {0}", System.Environment.CommandLine);

                var host = new ManagedServiceHost();
                host.ProcessCommandLine(args);
            }
            catch (FatalException fatalException)
            {
                const string msg = "ServiceHost cannot continue due to a fatal exception.";
                if (Log.IsFatalEnabled)
                    Log.Fatal(msg, fatalException);

                Console.WriteLine(msg);
                Console.WriteLine(fatalException);

                DisplayFatalExit();
            }
            catch(Exception ex)
            {
                const string msg = "An unhandled exception reached the service host.";
                if(Log.IsErrorEnabled) 
                    Log.Error(msg, ex);

                Console.WriteLine(msg);
                Console.WriteLine(ex);

                DisplayFatalExit();
            }
        }

        private static void DisplayFatalExit()
        {
            Console.WriteLine();
            Console.WriteLine(CommonResources.Program_DisplayFatalExit_Press_any_key_to_quit);
            Console.ReadKey();
        }
    }
}